package com.smallA.utils;


import java.io.File;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * RsaUtils
 *
 * @author 君未洋
 */
public class RsaUtils {

    private static final int DEFAULT_KEY_SIZE = 2048;

    /**
     * 从文件中获取公钥
     */
    public static PublicKey getPublicKey(String filename) throws Exception {
        byte[] bytes = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvAmFo83RtCxdDmybowO73mnQNxRALpEjmAtzCVPI0ax/msGAhEsPWUOxykUE2jlbv2Cg7hKSMiYbv9wzxlBw8kntCSg6qpNV5P7+NPnidnQz5oIl8hT8J7ZnCIWNxbdqX1LbA6/VYuVGTdxRgNw2vXQBC1GIWyOCLrsQnmCJQv8wmigoNgvv57f3rd7BcJ5wztO+FdOaVAp6NRELso+NyIvEFiHLswII76fJpr/KlNRNWSjUK0UzWr/D351PBBzUJryGDgN1vq/qzklq6c1BfyuUtZbG2Hhw0W5O6dyK0QgJqBTsICVLm00zDEZyOze6C4a8DO82C8BMwDSS24jQxwIDAQAB".getBytes();//readFile(filename);
        return getPublicKey(bytes);
    }

    /**
     * 从文件中获取密钥
     */
    public static PrivateKey getPrivateKey(String filename) throws Exception {
        byte[] bytes = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC8CYWjzdG0LF0ObJujA7veadA3FEAukSOYC3MJU8jRrH+awYCESw9ZQ7HKRQTaOVu/YKDuEpIyJhu/3DPGUHDySe0JKDqqk1Xk/v40+eJ2dDPmgiXyFPwntmcIhY3Ft2pfUtsDr9Vi5UZN3FGA3Da9dAELUYhbI4IuuxCeYIlC/zCaKCg2C+/nt/et3sFwnnDO074V05pUCno1EQuyj43Ii8QWIcuzAgjvp8mmv8qU1E1ZKNQrRTNav8PfnU8EHNQmvIYOA3W+r+rOSWrpzUF/K5S1lsbYeHDRbk7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69Jqot1wv3wiGUHMSKWXWck2IzL/2iRCggQ4QKBgHNDcuY7/lvui+KCMid+zc9ctp6YE2iD0un8duIJxW092OVaWxqCTpcKTGZbKnGRGguH1lYmkuBUgWAV3/p1vtgUlOY6GdesJLsFl2d2WoUde+wRcnEh+LG2OFGe9Pbv4iSl9wSHA1gzkcOwJs0t7dXpTIq17WW77uyArAT/tpc1".getBytes();//readFile(filename);
        return getPrivateKey(bytes);
    }

    /**
     * 获取公钥
     */
    public static PublicKey getPublicKey(byte[] bytes) throws Exception {
        bytes = Base64.getDecoder().decode(bytes);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePublic(spec);
    }

    /**
     * 获取密钥
     */
    public static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
        bytes = Base64.getDecoder().decode(bytes);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePrivate(spec);
    }

    /**
     * 根据密文生成rsa公钥和私钥,并写入指定的文件
     */
    public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret, int keySize) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom secureRandom = new SecureRandom(secret.getBytes());
        keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        //获取公钥并写出
        byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
        publicKeyBytes = Base64.getEncoder().encode(publicKeyBytes);
        writeFile(publicKeyFilename, publicKeyBytes);
        byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
        privateKeyBytes = Base64.getEncoder().encode(privateKeyBytes);
        writeFile(privateKeyFilename, privateKeyBytes);
    }

    private static byte[] readFile(String fileName) throws Exception {
        return Files.readAllBytes(new File(fileName).toPath());
    }

    private static void writeFile(String destPath, byte[] bytes) throws Exception {
        File dest = new File(destPath);
        if (!dest.exists()) {
            dest.createNewFile();
        }
        Files.write(dest.toPath(), bytes);
    }
}
